<template>
  <inline-Modal :visible="visible" :showOk="false">
    <div class="wrapPage-container custom-knowledgeBase-container">
      <div class="screen-conditions-container">
        <ScreenConditions :isDataType="false">
          <template slot="conditions">
            <a-input
              v-model="condition.name"
              placeholder="请输入任务名称"
            ></a-input>
            <a-range-picker
              :placeholder="['开始日期', '开始日期']"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
              v-model="condition.defaultTime"
              @change="search()"
            >
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
          </template>
          <template slot="operate">
            <a-button class="cu-btn-primary" icon="search" @click="search()">
              查询
            </a-button>
            <a-button class="cu-btn-filter" icon="reload" @click="reset()">
              重置
            </a-button>
            <a-button class="back-button" @click="goBack()">返回</a-button>
          </template>
        </ScreenConditions>
      </div>
      <div class="result-body-warp">
        <div class="drawing-container">
          <div class="header">{{ menuName }}</div>
          <div class="tree-container">
            <a-empty v-if="treeData.length == 0" />
            <a-tree
              v-else
              show-icon
              show-line
              v-model="checkedKeys"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'childList',
                title: 'name',
                key: 'uuid',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <template slot="title" slot-scope="{ name }">
                <div class="custom-tree-title-warp">
                  <div class="title" :title="name">
                    {{ name }}
                  </div>
                </div>
              </template>
            </a-tree>
          </div>
        </div>
        <div class="right-container">
          <div class="tabs-header">
            <div
              class="tabs-item-container"
              :class="[componentKey == 'tableCard' && 'atcive']"
              @click="handleTabActive('tableCard')"
            >
              任务项
            </div>
            <div
              class="tabs-item-container"
              :class="[componentKey == 'ganttCard' && 'atcive']"
              @click="handleTabActive('ganttCard')"
            >
              甘特图
            </div>
            <!-- <div
              class="tabs-item-container"
              :class="[componentKey == 'modelCard' && 'atcive']"
              @click="handleTabActive('modelCard')"
            >
              模型
            </div> -->
          </div>
          <div class="main-container">
            <!-- 版本信息 -->
            <div class="version-container">
              <div class="version-info">
                <div class="info-item">
                  <span class="name">
                    项目名称：
                  </span>
                  {{ currentVersion.proName || "-" }}
                </div>
                <div class="info-item">
                  <span class="name">编制人：</span>
                  {{ currentVersion.creator }}
                </div>
                <div class="info-item">
                  <span class="name">编制时间：</span>
                  {{ currentVersion.createTime }}
                </div>
              </div>
              <div class="version-info">
                <div class="info-item">
                  <span class="name" :title="currentVersion.name">
                    版本名称：
                  </span>
                  {{ currentVersion.name || "-" }}
                </div>
                <div class="info-item">
                  <span class="name">版本号：</span>
                  {{ currentVersion.code || "-" }}
                </div>
                <div class="info-item">
                  <span class="name">状态：</span>
                  <span :class="[filterStatusClass(currentVersion.status)]">
                    {{ currentVersion.status | filterStatusType }}
                  </span>
                </div>
              </div>
              <!-- 甘特图 -->
              <a-dropdown
                class="selectDate"
                v-if="componentKey == 'ganttCard' && treeData.length > 0"
              >
                <a-menu slot="overlay" @click="ganttChangeDateView($event)">
                  <a-menu-item :key="1"> 日视图 </a-menu-item>
                  <a-menu-item :key="2"> 周视图 </a-menu-item>
                  <a-menu-item :key="3"> 月视图 </a-menu-item>
                  <a-menu-item :key="4"> 季视图 </a-menu-item>
                </a-menu>
                <a-button> {{ ganttText }} <a-icon type="down" /> </a-button>
              </a-dropdown>
            </div>
            <div class="component-page">
              <components
                ref="componentCard"
                :is="componentKey"
                :visible="componentVisible"
                v-if="componentVisible"
                @ok="adjustOk"
                @versionEdit="handleVersionEdit"
                @socketInfo="handleSocket"
              ></components>
            </div>
          </div>
        </div>
      </div>
    </div>
  </inline-Modal>
</template>

<script>
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
//列表
import tableCard from "./tableCard.vue";
//甘特图
import ganttCard from "./ganttCard.vue";
//模型
import modelCard from "./modelCard.vue";

import {
  getPlanControlVersion,
  getTreeList,
  getTreeListDraft,
  getTreeListHistory,
} from "@/api/progressManage";
export default {
  inject: ["moduleSource"],
  provide() {
    return {
      versionSource: () => this.currentVersion,
      treeItemSource: () => this.currentTreeItem,
      conditionsSource: () => this.condition,
      firstIndex: () => this,
    };
  },
  components: {
    ScreenConditions,
    tableCard,
    ganttCard,
    modelCard,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      //查询条件
      condition: {
        //项目
        tenantCode: "",
        //名称
        name: "",
        //时间
        defaultTime: [],
      },
      //左侧树
      treeLoading: false,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      //树节点
      currentTreeItem: {},
      //版本信息
      currentVersion: {},
      //锁定信息
      lockInfo: {},
      //组件
      componentKey: "tableCard",
      componentVisible: true,
      //甘特图
      ganttView: 1,
      ganttText: "日视图",
      //
      isShow: true,
      operateType: 2,
    };
  },
  computed: {
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  filters: {
    //校验状态
    filterStatusType(val) {
      switch (Number(val)) {
        case -1:
          return "待提交";

        case 0:
          return "待提交";

        case 1:
          return "审批中";

        case 2:
          return "审批通过";

        case 3:
          return "驳回";

        case 4:
          return "已发布";

        case 5:
          return "已归档";

        default:
          return "-";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.condition.tenantCode = this.parameter.proCode;
          this.getVersionData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getTreeList,
    getTreeListDraft,
    getTreeListHistory,

    //查询版本号
    getVersionData() {
      let { tenantCode = "" } = this.condition;
      return new Promise((reslove, reject) => {
        getPlanControlVersion({
          proCode: tenantCode,
          type: this.moduleSource(),
          orgCode: "",
        })
          .then((res) => {
            this.currentVersion = res?.data ?? {};
            this.lockInfo = JSON.parse(this.currentVersion?.lockInfo ?? "{}");
            this.getTreeData();
            reslove();
          })
          .catch(() => {
            this.lockInfo = {};
            this.currentVersion = {};
            reject();
          });
      });
    },
    //查询一级节点
    getTreeData() {
      let { tenantCode = "" } = this.condition;
      let { uuid = "", status = "" } = this.currentVersion;
      if (!uuid) {
        this.selectedKeys = [];
        this.expandedKeys = [];
        this.currentTreeItem = [];
        this.treeData = [];
        this.$nextTick(() => {
          this.$refs?.["componentCard"]?.clearData();
        });
        return;
      }
      this.treeLoading = true;
      return new Promise((resolve, reject) => {
        let apiUrl = "";
        if (status == 4) {
          //正式
          apiUrl = "getTreeList";
        } else if (status == 5) {
          //历史记录
          apiUrl = "getTreeListHistory";
        } else {
          //草稿
          apiUrl = "getTreeListDraft";
        }
        this[apiUrl]({
          proCode: tenantCode,
          versionId: uuid,
          nodeType: this.moduleSource(),
          orgCode: "",
        })
          .then((res) => {
            let source = res?.data || [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childList"
            );
            this.treeData = filterData ?? [];
            this.treeData.length > 0 && this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.autoExpandParent = true;
            this.treeLoading = false;
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childList");
      let item = flatData.find((v) => !v.childList || v.childList.length == 0);
      this.expandedKeys = [item.uuid];
      this.selectedKeys = [item.uuid];
      this.currentTreeItem = item;
      this.getData();
    },

    //展开
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //树选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.currentTreeItem = info.node.dataRef;
      this.getData();
    },

    //查询数据
    async getData() {
      await this.$nextTick();
      this.$refs?.["componentCard"]?.getData();
    },

    //搜索
    search() {
      this.getData();
    },

    handleTabActive(key) {
      this.componentKey = key;
      this.getData();
      if (!this.isShow) {
        this.$nextTick(() => {
          this.$refs?.["componentCard"]?.setPage();
        });
      }
    },

    //重置
    reset() {
      this.condition.name = "";
      this.condition.defaultTime = [];
      this.getData();
    },

    //新增版本-新版本信息
    adjustOk(data) {
      this.isShow = false;
      this.operateType = 1;
      this.currentVersion = data;
      //刷新左侧树
      this.getTreeData();
    },

    //版本管理-编辑/查看
    handleVersionEdit(data = {}, flag, type) {
      this.isShow = flag;
      this.operateType = type;
      //
      if (!this.isEmptyObject(data)) {
        this.currentVersion = data;
        //刷新左侧树
        this.getTreeData();
      }
    },

    //甘特图日月年季切换
    ganttChangeDateView(info) {
      let { key } = info;
      this.ganttView = key;
      switch (key) {
        case 1:
          this.ganttText = "日视图";
          break;
        case 2:
          this.ganttText = "周视图";
          break;
        case 3:
          this.ganttText = "月视图";
          break;
        case 4:
          this.ganttText = "季视图";
          break;
        default:
          break;
      }
      this.$nextTick(() => {
        this.$refs?.["componentCard"]?.initGantt();
      });
    },

    //是否是空对象
    isEmptyObject(obj) {
      return Object.keys(obj).length == 0;
    },

    //接受Socket消息
    handleSocket(data) {
      this.lockInfo = data;
    },

    //校验状态
    filterStatusClass(val) {
      switch (Number(val)) {
        case -1:
          return "default";

        case 0:
          return "default";

        case 1:
          return "warning";

        case 2:
          return "progress";

        case 3:
          return "reject";

        case 4:
          return "success";

        case 5:
          return "place-file";

        default:
          return "";
      }
    },

    //返回
    goBack() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  background-color: #f0f2f5;
  /deep/.header {
    display: none;
  }
  /deep/.main {
    padding: 0;
    overflow: hidden !important;
  }
  .wrapPage-container {
    height: 100%;
    overflow: hidden;
    .back-button {
      position: absolute;
      right: 16px;
    }
    .result-body-warp {
      .right-container {
        .tabs-header {
          user-select: none;
          display: flex;
          align-items: center;
          height: 56px;
          border-bottom: 1px solid #d9d9d9;
          padding: 0 16px;
          box-sizing: border-box;
          .tabs-item-container {
            height: 100%;
            cursor: pointer;
            width: 100px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 16px;
            color: #8a9295;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            &.atcive {
              color: #1890ff;
              &::after {
                content: "";
                width: 100px;
                height: 2px;
                background: #1890ff;
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translate(-50%);
              }
            }
          }
        }
        .main-container {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          .version-container {
            box-sizing: border-box;
            padding: 14px 20px 14px 20px;
            display: flex;
            flex-direction: column;
            position: relative;
            .version-info {
              display: flex;
              align-items: center;
              &:nth-child(1) {
                margin-bottom: 10px;
              }
              .info-item {
                flex: 1;
                font-family: Microsoft YaHei;
                font-weight: 400;
                font-size: 14px;
                color: #333333;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                .name {
                  color: #8a9295;
                }
                .default {
                  color: #8c8c8c;
                }
                .success {
                  color: #4bc964;
                }
                .warning {
                  color: #f07f17;
                }
                .reject {
                  color: #ff3f4a;
                }
                .progress {
                  color: #a07df1;
                }
                .place-file {
                  color: #3b6bf5;
                }
              }
            }
            .selectDate {
              position: absolute;
              right: 20px;
              bottom: 14px;
            }
          }
          .component-page {
            flex: 1;
            overflow: hidden;
          }
        }
      }
    }
  }
}
</style>
